package pers.cz.netty;

import pers.cz.config.NettyItem;
import pers.cz.jefconfig.config.JefConfiguration;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @program: PostGirl-panent
 * @description: 客户端
 * @author: Cheng Zhi
 * @create: 2022-07-01 13:00
 **/
public class Client implements LogMessageListener{

    static SocketChannel channel;

    static {
        try {
            Selector open = Selector.open();
            channel = SocketChannel.open();
            channel.connect(new InetSocketAddress(JefConfiguration.get(NettyItem.NETTY_SERVER_HOST), JefConfiguration.getInt(NettyItem.NETTY_SERVER_PORT, 8888)));
            channel.configureBlocking(false);
            channel.register(open, 0, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送消息
     * @param msg
     * @throws IOException
     */
    public static void sendMsg(String msg) throws IOException {
        channel.write(Charset.forName(StandardCharsets.UTF_8.name()).encode(msg));
    }

}
